<!--
  Copyright [2025] [OBARA (Nanjing) Electromechanical Co., Ltd]

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->


{% extends 'base_en.html' %}

{% block title %}Product Search - OBARA Welding Gun Selection Database{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="text-center mb-4 fade-in-up">
            <h1 class="display-5 fw-bold">
                <i class="bi bi-search me-3"></i>
                SERVO GUN Product Search
            </h1>
            <p class="lead text-muted">Please select a category and fill in the search criteria</p>
        </div>
        
        <!-- AI Smart Search Card -->
        <div class="card mb-4 fade-in-up" style="border: 2px solid #007bff;">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">
                    <i class="bi bi-robot me-2"></i>
                    AI Smart Search(Testing function, welcome to try, the results are for reference only)
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-9">
                        <label for="ai_query" class="form-label">
                            <i class="bi bi-chat-dots me-2"></i>
                            Please describe your welding gun requirements in natural language, AI will intelligently match suitable product numbers
                        </label>
                        <textarea class="form-control" id="ai_query" rows="1" style="resize: none;" 
                                placeholder="e.g.: Throat depth around 300, throat width around 450, 85 transformer, pressure around 4500 C gun"></textarea>
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="button" class="btn btn-primary w-100" id="ai_search_btn">
                            <i class="bi bi-magic me-2"></i>
                            AI Smart Search
                        </button>
                    </div>
                </div>
                
                <!-- AI Search Result Display Area -->
                <div id="ai_search_result" class="mt-3" style="display: none;">
                    <div class="alert alert-info">
                        <div id="ai_result_content"></div>
                        <div id="ai_result_actions" class="mt-2" style="display: none;">
                            <button type="button" class="btn btn-success" id="search_these_numbers">
                                <i class="bi bi-search me-2"></i>
                                Search These Numbers
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Loading Status -->
                <div id="ai_search_loading" class="mt-3 text-center" style="display: none;">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Searching...</span>
                    </div>
                    <p class="mt-2 text-muted">AI is analyzing your requirements,Waiting time is approximately 10 seconds, please wait...</p>
                </div>
            </div>
        </div>
        
        <div class="card mb-4 fade-in-up" style="border: 2px solid #28a745;">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0">
                    <i class="bi bi-funnel me-2"></i>
                    Regular Search
                </h5>
            </div>
            <div class="card-body">
                <form method="get" action="{% url 'clamps:search_results_en' %}" id="searchForm">
                    {% csrf_token %}
                <!-- Main search fields and image preview -->
                <div class="row g-3 mb-4">
                    <!-- Left two columns: input fields -->
                    <div class="col-md-8">
                        <div class="row g-3">
                            <!-- Row 1 -->
                            <!-- Product Category -->
                            <div class="col-md-6">
                                <label for="category" class="form-label">
                                    <i class="bi bi-diagram-3 me-2"></i>
                                    <span style="color: red; font-weight: bold;">Product Category</span> <span class="text-danger">*</span>
                                    <a href="/static/pdf/Product Search User Guide.pdf" target="_blank" class="btn btn-outline-info btn-sm ms-2" title="User Guide">
                                        <i class="bi bi-question-circle"></i>
                                    </a>
                                </label>
                                <select class="form-select" id="category" name="category">
                                    <option value="">Please select, required option</option>
                                    {% for category in categories %}
                                        {% if category.name in 'X2C-C,X2C-X' %}
                                            <option value="{{ category.id }}">{{ category.name }}(Recommended)</option>
                                        {% else %}
                                            <option value="{{ category.id }}">{{ category.name }}</option>
                                        {% endif %}
                                    {% endfor %}
                                </select>
                            </div>
                            
                            <!-- Sub-category Type -->
                            <div class="col-md-6">
                                <label for="sub_category_type" class="form-label">
                                    <i class="bi bi-tags me-2"></i>
                                    Sub-category Type
                                </label>
                                <select class="form-select" id="sub_category_type" name="sub_category_type">
                                    <option value="">Please select, default is empty</option>
                                    <!-- Options loaded dynamically -->
                                </select>
                            </div>

                            <!-- Row 2 -->
                            <!-- Throat Depth -->
                            <div class="col-md-6">
                                <label for="throat_depth" class="form-label">
                                    <i class="bi bi-rulers me-2"></i>
                                    Throat Depth
                                </label>
                                <input type="text" class="form-control" id="throat_depth" name="throat_depth" placeholder="e.g.: ~350, 350~600, 600~">
                            </div>
                            
                            <!-- Throat Width -->
                            <div class="col-md-6">
                                <label for="throat_width" class="form-label">
                                    <i class="bi bi-arrows-expand me-2"></i>
                                    Throat Width
                                </label>
                                <input type="text" class="form-control" id="throat_width" name="throat_width" placeholder="e.g.: ~350, 350~600, 600~">
                            </div>

                            <!-- Row 3 -->
                            <!-- Transformer -->
                            <div class="col-md-6">
                                <label for="transformer" class="form-label">
                                    <i class="bi bi-cpu me-2"></i>
                                    Transformer
                                </label>
                                <select class="form-select" id="transformer" name="transformer">
                                    <option value="">Please select, default is empty</option>
                                    <!-- Options loaded dynamically -->
                                </select>
                            </div>
                            
                            <!-- Clamping Force -->
                            <div class="col-md-6">
                                <label for="clamping_force" class="form-label">
                                    <i class="bi bi-lightning me-2"></i>
                                    Clamping Force
                                </label>
                                <input type="text" class="form-control" id="clamping_force" name="clamping_force" placeholder="e.g.: ~3500, 3500~5500, 5500~">
                            </div>
                        </div>
                    </div>

                    <!-- Right column: Image display area -->
                    <div class="col-md-4">
                        <div class="card h-100">
                            <div class="card-body text-center d-flex flex-column justify-content-center">
                                <h5 class="card-title">Sub-category Option Preview</h5>
                                <p class="text-muted small mb-2">Preview only shows window style, ignoring transformer orientation and gearbox type</p>
                                <img id="product_image" src="/static/images/No image available.png" alt="Product Preview" class="img-fluid" style="max-height: 250px;">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Advanced Search Fields -->
                <div class="mt-4">
                    <button class="btn btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#advancedSearch">
                        <i class="bi bi-gear me-2"></i>
                        Advanced Search Options
                    </button>
                </div>
                
                <div class="collapse mt-3" id="advancedSearch">
                    <div class="card">
                        <div class="card-body">
                            <!-- All advanced fields (static + dynamic) are placed in this row -->
                            <div class="row g-3" id="advanced-fields-container">
                                <!-- Drawing No. 1(o) -->
								<div class="col-md-4">
									<label for="drawing_no_1" class="form-label">
										<i class="bi bi-file-earmark-text me-2"></i>
										Drawing No. 1(o)
									</label>
									<input type="text" class="form-control" id="drawing_no_1" name="drawing_no_1" 
										   placeholder="Weld gun drawing number, default is empty">
								</div>
                                
                                <!-- Description -->
                                <div class="col-md-4">
                                    <label for="description" class="form-label">
                                        <i class="bi bi-card-text me-2"></i>
                                        Description
                                    </label>
                                    <input type="text" class="form-control" id="description" name="description" placeholder="Customer description, default is empty">
                                </div>
                                
                                <!-- Stroke -->
                                <div class="col-md-4">
                                    <label for="stroke" class="form-label">
                                        <i class="bi bi-arrows-move me-2"></i>
                                        Stroke
                                    </label>
                                    <input type="text" class="form-control" id="stroke" name="stroke" placeholder="e.g.: ~90, 100~190, 210~">
                                </div>
                                
								<!-- MOTOR Manufacturer -->
								<div class="col-md-4">
									<label for="motor_manufacturer" class="form-label">
										<i class="bi bi-gear-wide-connected me-2"></i>
										MOTOR Manufacturer
									</label>
									<select class="form-select" id="motor_manufacturer" name="motor_manufacturer">
										<option value="">Please select, default is empty</option>
										<option value="FANUC">FANUC</option>
										<option value="KUKA">KUKA</option>
										<option value="YASKAWA">YASKAWA</option>
										<option value="ABB">ABB</option>
										<option value="TOLOMATIC">TOLOMATIC</option>
										<option value="多摩川">Tamagawa</option>
										<option value="PANASONIC">PANASONIC</option>
										<option value="DIAKONT">DIAKONT</option>
										<option value="SEW">SEW</option>
										<option value="SANYO">SANYO</option>
										<option value="其他">Others</option>
									</select>
								</div>
								
								<!-- Transformer Placement -->
                                <div class="col-md-4">
                                    <label for="transformer_placement" class="form-label">
                                        <i class="bi bi-compass me-2"></i>
                                        Transformer Placement
                                    </label>
                                    <select class="form-select" id="transformer_placement" name="transformer_placement">
                                        <option value="">Please select, default is empty</option>
                                        <option value="水平">Horizontal</option>
                                        <option value="竖直">Vertical</option>
                                        <option value="下置">Bottom</option>
                                        <option value="上置">Top</option>
                                        <option value="右置">Right</option>
                                        <option value="其他">Others</option>
                                    </select>
                                </div>
                                
                                <!-- Has Balance -->
                                <div class="col-md-4">
                                    <label for="has_balance" class="form-label">
                                        <i class="bi bi-water me-2"></i>
                                        Has Balance
                                    </label>
                                    <select class="form-select" id="has_balance" name="has_balance">
                                        <option value="">Please select, default is empty</option>
                                        <option value="有">Yes</option>
                                        <option value="无">No</option>
                                    </select>
                                </div>
                                
                                <!-- Weight -->
                                <div class="col-md-4">
                                    <label for="weight" class="form-label">
                                        <i class="bi bi-box me-2"></i>
                                        Weight
                                    </label>
                                    <input type="text" class="form-control" id="weight" name="weight" placeholder="e.g.: ~90, 90~120, 120~">
                                </div>
                                
                                <!-- Flange P.C.D -->
                                <div class="col-md-4">
                                    <label for="flange_pcd" class="form-label">
                                        <i class="bi bi-circle me-2"></i>
                                        Flange P.C.D
                                    </label>
                                    <select class="form-select" id="flange_pcd" name="flange_pcd">
                                        <option value="">Please select, default is empty</option>
                                        <option value="125">125</option>
                                        <option value="125-160">125-160</option>
                                        <option value="160">160</option>
                                        <option value="200">200</option>
                                        <option value="92">92</option>
                                        <option value="其他">Others</option>
                                    </select>
                                </div>
                                
                                <!-- Bracket Direction -->
                                <div class="col-md-4">
                                    <label for="bracket_direction" class="form-label">
                                        <i class="bi bi-arrow-up-right me-2"></i>
                                        Bracket Direction
                                    </label>
                                    <select class="form-select" id="bracket_direction" name="bracket_direction">
                                        <option value="">Please select, default is empty</option>
                                        <option value="右">Right</option>
                                        <option value="上">Up</option>
                                        <option value="前">Front</option>
                                        <option value="下">Down</option>
                                        <option value="后">Back</option>
                                        <option value="三维">3D</option>
                                        <option value="左">Left</option>
                                    </select>
                                </div>
                                
                                <!-- Water Circuit -->
                                <div class="col-md-4">
                                    <label for="water_circuit" class="form-label">
                                        <i class="bi bi-droplet me-2"></i>
                                        Water Circuit
                                    </label>
                                    <select class="form-select" id="water_circuit" name="water_circuit">
                                        <option value="">Please select, default is empty</option>
                                        <option value="1进1出">1 In 1 Out</option>
                                        <option value="2进2出">2 In 2 Out</option>
                                        <option value="3进3出">3 In 3 Out</option>
                                        <option value="1进2出">1 In 2 Out</option>
                                        <option value="2进3出">2 In 3 Out</option>
                                        <option value="1进3出">1 In 3 Out</option>
                                        <option value="其他">Others</option>
                                    </select>
                                </div>
                                
                                <!-- Dynamic fields will be inserted here (key change) -->
                                <div id="dynamic-fields-placeholder" class="contents"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Search Buttons -->
                <div class="text-center mt-4">
                    <button type="submit" class="btn btn-primary btn-lg px-5" id="searchSubmitBtn">
                        <i class="bi bi-search me-2"></i>
                        Search
					</button>
                    <button type="reset" class="btn btn-outline-secondary btn-lg px-5 ms-3">
                        <i class="bi bi-arrow-clockwise me-2"></i>
                        Reset Criteria
                    </button>
                </div>
                </form>
            </div>
        </div>
        
        <!-- Search Tips -->
        <div class="row mt-5">
            <div class="col-md-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-robot text-primary" style="font-size: 2rem;"></i>
                        <h5 class="card-title mt-3">AI Smart Search</h5>
                        <p class="card-text text-muted">Use natural language to describe your needs, AI automatically matches suitable welding gun products.</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-lightbulb text-warning" style="font-size: 2rem;"></i>
                        <h5 class="card-title mt-3">Search Tips</h5>
                        <p class="card-text text-muted">
                            All search criteria are optional. Leaving a field empty means no restriction on that condition.
                        </p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-funnel text-info" style="font-size: 2rem;"></i>
                        <h5 class="card-title mt-3">Precise Matching</h5>
                        <p class="card-text text-muted">
                            Numeric fields support precise matching, while text fields support fuzzy search.
                        </p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-download text-success" style="font-size: 2rem;"></i>
                        <h5 class="card-title mt-3">File Download</h5>
                        <p class="card-text text-muted">
                            PDF, STEP, and ZIP files can be downloaded directly from the search results.
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Mapping of category to sub-category types with English labels
        const categorySubTypes = {
            'X2C-C(Recommended)': [
                { label: 'Large', value: '大型' },
                { label: 'Special', value: '特殊' },
                { label: 'Crane Type', value: '仙鹤型' },
                { label: 'Small-Medium', value: '中小型' }
            ],
            'X2C-V2-C': [
                { label: 'Large', value: '大型' },
                { label: 'Special', value: '特殊' },
                { label: 'Crane Type', value: '仙鹤型' },
                { label: 'Small-Medium', value: '中小型' }
            ],
            'X2C-V3-C': [
                { label: 'Large', value: '大型' },
                { label: 'Small', value: '小型' }
            ],
            'X2C-X(Recommended)': [
                { label: 'Large', value: '大型' },
                { label: 'Special', value: '特殊' },
                { label: 'Small-Medium', value: '中小型' },
                { label: 'X', value: 'X' },
                { label: 'Y', value: 'Y' }
            ],
            'X2C-V2-X': [
                { label: 'Large', value: '大型' },
                { label: 'Special', value: '特殊' },
                { label: 'Small', value: '小型' },
                { label: 'Medium', value: '中型' },
                { label: 'X', value: 'X' },
                { label: 'Y', value: 'Y' }
            ],
            'X2C-V3-X': [
                { label: 'Large', value: '大型' },
                { label: 'Small', value: '小型' }
            ]
        };

        // Mapping of category to transformer types (original values)
        const categoryTransformerTypes = {
            'X2C-C(Recommended)': ['ITS85', 'DB6-100R1', 'RT552', 'RT752','RT906', 'NI110',  'BOSCH', '商科', 'DB6-90-510', 'RT452', 'RT706','DB6-225-510(B)', '其他'],
            'X2C-V2-C': ['DB6','其他'],
            'X2C-V3-C': ['ITS85','SMF-100', 'MF-100','DB6-90', 'DB6-100', 'BOSCH', '商科', '其他'],
            'X2C-X(Recommended)': ['ITS85', 'DB6-100R1', 'RT552', 'RT752','RT906', 'NI110',  'BOSCH', '商科', 'DB6-90-510', 'RT452', 'RT706','DB6-225-510(B)', '其他'],
            'X2C-V2-X': ['DB6','其他'],
            'X2C-V3-X': ['ITS85','SMF-100', 'MF-100','DB6-90', 'DB6-100', 'BOSCH', '商科', '其他']
        };
        
        // Formats the transformer type for display in English
        function formatTransformerDisplayText(type) {
            if (type === 'ITS85' || type === 'DB6-100R1') {
                return type + ' (Recommended)';
            }
            if (type === 'DB6-90-510' || type === 'DB6' || type === 'DB6-90') {
                return 'DB6-90';
            }
            if (type === '商科') {
                return 'Shangke';
            }
            if (type === '其他') {
                return 'Others';
            }
            return type;
        }

        // Updates the transformer dropdown options
        function updateTransformerOptions(categoryName) {
            const transformerSelect = document.getElementById('transformer');
            transformerSelect.innerHTML = '<option value="">Please select, default is empty</option>';
            
            if (categoryName && categoryTransformerTypes[categoryName]) {
                categoryTransformerTypes[categoryName].forEach(transformerType => {
                    const option = document.createElement('option');
                    
                    // **CORE LOGIC**
                    // 1. `option.value` stores the original value for form submission.
                    option.value = transformerType;
                    // 2. `option.textContent` stores the formatted English text for display.
                    option.textContent = formatTransformerDisplayText(transformerType);
                    
                    transformerSelect.appendChild(option);
                });
            }
        }
        
        // Update dynamic fields (key addition)
        function updateDynamicFields(categoryName) {
            // 1. Clear previously added dynamic fields
            currentDynamicFields.forEach(field => field.remove());
            currentDynamicFields = [];

            let fieldsToCreate = [];
            
            if (categoryName && categoryName.includes('-C')) {
                fieldsToCreate.push(
                    {
                        id: 'electrode_arm_end',
                        label: 'Electrode Arm End',
                        type: 'select',
                        options: [
                            { value: '', text: 'Please select, default is empty' },
                            { value: '握杆（铝）', text: 'Grip Rod (Aluminum)' },
                            { value: 'TIP BASE（F 型）', text: 'TIP BASE (F Type)' },
                            { value: '握杆（SBA）', text: 'Grip Rod (SBA)' },
                            { value: 'TIP BASE（G 型）', text: 'TIP BASE (G Type)' },
                            { value: 'GUN HEAD（?36）', text: 'GUN HEAD (?36)' },
                            { value: 'GUN HEAD（?45）', text: 'GUN HEAD (?45)' },
                            { value: 'GUN HEAD（?40）', text: 'GUN HEAD (?40)' },
                            { value: 'GUN HEAD（?50）', text: 'GUN HEAD (?50)' },
                            { value: 'GUN HEAD（?60）', text: 'GUN HEAD (?60)' },
                            { value: '握杆?45（铝）', text: 'Grip Rod ?45 (Aluminum)' },
                            { value: '握杆?50（铝）', text: 'Grip Rod ?50 (Aluminum)' },
                            { value: '特殊', text: 'Special' },
                            { value: '其他', text: 'Others' }
                        ]
                    },
					{
                        id: 'eccentricity',
                        label: 'Eccentricity Distance',
                        icon: 'bi-arrows-angle-contract',
                        placeholder: 'e.g.: 10~50, 50~'
                    }
                );
            } else if (categoryName && categoryName.includes('-X')) {
                fieldsToCreate = [
                    { id: 'static_arm_front_length', label: 'Static Arm Front Length', icon: 'bi-arrows-expand', placeholder: 'e.g.: ~246, 246~346, 346~' },
                    { id: 'static_arm_front_height', label: 'Static Arm Front Height', icon: 'bi-arrows-vertical', placeholder: 'e.g.: ~50, 50~100, 100~' },
                    { id: 'moving_arm_front_length', label: 'Moving Arm Front Length', icon: 'bi-arrows-expand', placeholder: 'e.g.: ~246, 246~346, 346~' },
                    { id: 'moving_arm_front_height', label: 'Moving Arm Front Height', icon: 'bi-arrows-vertical', placeholder: 'e.g.: ~50, 50~100, 100~' }
                ];
            }

            // 2. Create and insert new dynamic fields
            fieldsToCreate.forEach(field => {
                const fieldDiv = document.createElement('div');
                fieldDiv.className = 'col-md-4';
                
                if (field.type === 'select') {
                    let optionsHtml = field.options.map(option => 
                        `<option value="${option.value}">${option.text}</option>`
                    ).join('');
                    
                    fieldDiv.innerHTML = `
                        <label for="${field.id}" class="form-label">
                            <i class="bi ${field.icon || 'bi-tools'} me-2"></i>
                            ${field.label}
                        </label>
                        <select class="form-select" id="${field.id}" name="${field.id}">
                            ${optionsHtml}
                        </select>
                    `;
                } else {
                    fieldDiv.innerHTML = `
                        <label for="${field.id}" class="form-label">
                            <i class="bi ${field.icon} me-2"></i>
                            ${field.label}
                        </label>
                        <input type="text" class="form-control" id="${field.id}" name="${field.id}" placeholder="${field.placeholder}">
                    `;
                }
                
                // Insert new fields before the placeholder, so they appear at the placeholder's position
                dynamicFieldsPlaceholder.parentNode.insertBefore(fieldDiv, dynamicFieldsPlaceholder);
                currentDynamicFields.push(fieldDiv); // Save reference to new fields for later cleanup
            });
        }

        // Dynamic fields management (key addition)
        let currentDynamicFields = [];
        const dynamicFieldsPlaceholder = document.getElementById('dynamic-fields-placeholder');
        
        const defaultImagePath = '/static/images/No image available.png';
        const productImageElement = document.getElementById('product_image');

        // Form reset functionality
        document.querySelector('button[type="reset"]').addEventListener('click', function() {
            document.getElementById('searchForm').reset();
            document.querySelectorAll('select').forEach(select => {
                select.selectedIndex = 0;
            });
            updateSubCategoryOptions('');
            updateTransformerOptions('');
            updateDynamicFields('');
            productImageElement.src = defaultImagePath;
        });
        
        // Handle category selection change
        document.getElementById('category').addEventListener('change', function() {
            const categorySelect = this;
            const selectedText = categorySelect.options[categorySelect.selectedIndex].text;
            if (selectedText && selectedText !== 'Please select, optional') {
                updateSubCategoryOptions(selectedText);
                updateTransformerOptions(selectedText);
                updateDynamicFields(selectedText);
                updateProductImage();
            } else {
                updateSubCategoryOptions('');
                updateTransformerOptions('');
                updateDynamicFields('');
                productImageElement.src = defaultImagePath;
            }
        });

        // Handle sub-category type selection change
        document.getElementById('sub_category_type').addEventListener('change', function() {
            updateProductImage();
        });
        
        // Update sub-category type options with English labels
        function updateSubCategoryOptions(categoryName) {
            const subCategorySelect = document.getElementById('sub_category_type');
            subCategorySelect.innerHTML = '<option value="">Please select, default is empty</option>';
            
            if (categoryName && categorySubTypes[categoryName]) {
                categorySubTypes[categoryName].forEach(item => {
                    const option = document.createElement('option');
                    option.value = item.value; // Submit the original Chinese value
                    option.textContent = item.label; // Display the English label
                    subCategorySelect.appendChild(option);
                });
            }
        }

        // Update product image based on selected values
        function updateProductImage() {
            const categorySelect = document.getElementById('category');
            const subCategorySelect = document.getElementById('sub_category_type');

            const selectedCategoryText = categorySelect.options[categorySelect.selectedIndex].text;
            // Use .value to get the original Chinese value needed for the image name
            const selectedSubCategoryValue = subCategorySelect.value;

            if (selectedCategoryText && selectedSubCategoryValue) {
                // Construct image name using the original Chinese value for sub-category
                const imageName = `${selectedCategoryText}-${selectedSubCategoryValue}.png`;
                const imagePath = `/static/images/${imageName}`;
                
                const img = new Image();
                img.onload = () => { productImageElement.src = imagePath; };
                img.onerror = () => { productImageElement.src = defaultImagePath; };
                img.src = imagePath;
            } else {
                productImageElement.src = defaultImagePath;
            }
        }

        // Initial setup on page load
        const initialCategorySelect = document.getElementById("category");
        const initialCategoryText = initialCategorySelect.options[initialCategorySelect.selectedIndex].text;
        if (initialCategoryText && initialCategoryText !== 'Please select, required option') {
            updateSubCategoryOptions(initialCategoryText);
            updateTransformerOptions(initialCategoryText);
            updateDynamicFields(initialCategoryText);
            updateProductImage();
        } else {
            updateSubCategoryOptions('');
            updateTransformerOptions('');
            updateDynamicFields('');
            productImageElement.src = defaultImagePath;
        }
        if (!document.getElementById('category').value) {
            document.getElementById('category').focus();
        }

        // AI Search functionality
        document.getElementById('ai_search_btn').addEventListener('click', function() {
            const query = document.getElementById('ai_query').value.trim();
            if (!query) {
                alert('Please enter your requirement description');
                return;
            }
            
            // Show loading state
            document.getElementById('ai_search_loading').style.display = 'block';
            document.getElementById('ai_search_result').style.display = 'none';
            
            // Send AJAX request
            fetch('/api/ai_search/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: JSON.stringify({
                    query: query
                })
            })
            .then(response => response.json())
            .then(data => {
                // Hide loading state
                document.getElementById('ai_search_loading').style.display = 'none';
                
                if (data.success) {
                    // Display results
                    const resultContent = document.getElementById('ai_result_content');
                    const resultActions = document.getElementById('ai_result_actions');
                    
                    if (data.data === '未找到符合要求的焊枪') {
                        resultContent.innerHTML = '<strong>Search Result:</strong> No suitable welding gun found<br><small class="text-muted">Please adjust your search criteria and try again</small>';
                        resultActions.style.display = 'none';
                    } else {
                        resultContent.innerHTML = '<strong>Found the following part numbers:</strong><br>' + data.data;
                        resultActions.style.display = 'block';
                        
                        // Store part number data for later use
                        document.getElementById('search_these_numbers').setAttribute('data-numbers', data.data);
                    }
                    
                    document.getElementById('ai_search_result').style.display = 'block';
                } else {
                    alert('Search failed: ' + data.error);
                }
            })
            .catch(error => {
                document.getElementById('ai_search_loading').style.display = 'none';
                alert('Network error, please try again later');
                console.error('Error:', error);
            });
        });
        
        // "Search These Numbers" button functionality
        document.getElementById('search_these_numbers').addEventListener('click', function() {
            const numbers = this.getAttribute('data-numbers');
            if (numbers) {
                // Clear all search conditions
                document.getElementById('searchForm').reset();
                
                // Fill part numbers into drawing_no_1 field
                document.getElementById('drawing_no_1').value = numbers;
                
                // Submit form
                document.getElementById('searchForm').submit();
            }
        });

        // Form submission validation
        document.getElementById('searchForm').addEventListener('submit', function(event) {
            const categoryValue = document.getElementById('category').value;
            const drawingNo1Value = document.getElementById('drawing_no_1').value.trim();
            if (!categoryValue && !drawingNo1Value) {
                event.preventDefault(); // Prevent form submission
                alert('Product category is required, please select one!');
                location.reload(); 
            }
        });
    });
</script>
{% endblock %}